﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;

public class VCam : MonoBehaviour {

	public int vcam_port = 8001;

	UdpClient udp;
	
	// Use this for initialization
	void Start () {
		IPEndPoint udp_ep = new IPEndPoint (IPAddress.Any, vcam_port);
		udp = new UdpClient (udp_ep);
		udp.BeginReceive (new AsyncCallback (Udp_IncomingData), null);
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnApplicationQuit() {
		udp.Close ();
	}

	private void Udp_IncomingData(IAsyncResult ar)
	{
		try
		{
			// receive bytes
			IPEndPoint anyRemoteIP = new IPEndPoint(IPAddress.Any, 0);
			byte[] recvedData = udp.EndReceive(ar, ref anyRemoteIP);

			// encode UTF8-coded bytes to text format
			//string text = Encoding.UTF8.GetString(data);

			udp.BeginReceive(new AsyncCallback(Udp_IncomingData), null);
		}
		catch (Exception err)
		{
			Debug.Log(err.ToString());
		}
	}
}
